/*
 * This file is part of Annuaire.
 *
 * Annuaire is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Annuaire is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Annuaire.  If not, see <http://www.gnu.org/licenses/>.
 */

/** 
 * Cette servlet crée le ficheir PDF en fonction des reseultats de la recherche,
 * et envoie le fichier au client
 */
package org.miage.annuaire.servlet;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import org.miage.annuaire.data.XmlDataAccessImpl;
import org.miage.annuaire.pdf.xml2pdf;
import org.w3c.dom.Document;

/**
 *
 * @author comeulie
 */
public class Pdf extends HttpServlet {
   
	private static final long serialVersionUID = 1L;

	/** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, ParserConfigurationException {
        ServletOutputStream stream = null;
        BufferedInputStream buf = null;
        try {
            // Recupere le fichier de style ------------------------------------
            InputStream xsl = getServletContext().getResourceAsStream("WEB-INF/configurationXML/pdf.xsl");
            
            // Recupere le premier parametre "all" ou "only" -------------------
            // Appelle la fonction getAllStructures() ou gatStructuresByKeys
            Enumeration<String> param = request.getParameterNames();
            Document listeDesMembres = null;
            XmlDataAccessImpl data = new XmlDataAccessImpl();
            if( param.hasMoreElements() ) {                
                if (param.nextElement().toString().equals("all")) {
                    listeDesMembres = data.getAllStructures();
                } else {
                    // Cree une liste des clefs des structures a rechercher ----
                    ArrayList<String> list = new ArrayList<String>();
                    while( param.hasMoreElements() )
                        list.add( param.nextElement().toString() );
                    listeDesMembres = data.getStructuresByKeys(list);
                }
            }

            // Transforme le resultat en fichier PDF ---------------------------
            xml2pdf pdf2 = new xml2pdf();
            FileInputStream f = pdf2.extract2stream(listeDesMembres,xsl,getServletContext().getResource("").toString());

            // Envoie le fichier au client : set response headers --------------
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment; filename=Annuaire.pdf");
            stream = response.getOutputStream();

            buf = new BufferedInputStream(f);
            int readBytes = 0;

            while ( (readBytes = buf.read()) != -1)
                stream.write(readBytes);        
        } finally { 
            if (stream != null)  stream.close();
            if (buf != null)     buf.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(Pdf.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(Pdf.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public String execute() {
        return "success";
    }
}
